from django.shortcuts import render
from rest_framework.generics import GenericAPIView
from rest_framework.views import APIView
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from rest_framework.response import Response

from carts.utils import merge_cart
from oauth.models import OAuthQQUser
from . import serializers

from oauth.utils import generate_sign_openid
# from .models import OAuthQQUser

class OAuthQQLoginView(APIView):
    def get(self, request):
        # 获取参数
        state = request.query_params.get("state", "/")
        # 创建QQ对象
        oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                           redirect_uri=settings.QQ_REDIRECT_URI, state=state)
        # 返回QQ登陆页面
        login_url = oauth_qq.get_qq_url()
        return Response({"auth_url": login_url})  # 将auth_url作为前端JS代码的key传值过去


class OAuthQQUserView(GenericAPIView):
    serializer_class = serializers.OAuthQQUserSerializer

    def get(self, request):
        # 获取code参数, 效验
        code = request.query_params.get("code")
        if not code:
            return Response("code丢失")

        # 根据code获取access_token
        oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                           client_secret=settings.QQ_CLIENT_SECRET,
                           redirect_uri=settings.QQ_REDIRECT_URI,
                           state='/')

        access_token = oauth_qq.get_access_token(code)
        # 根据access_token获取openid
        openid = oauth_qq.get_open_id(access_token)

        # 通过openid查询QQ对象用户
        try:
            oauth_qq_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
        # except Exception as e:
            # 初次授权
            sign_openid = generate_sign_openid(openid)  # 使用定义的加密方法对openid进行加密
            return Response({"access_token": sign_openid})  # 将加密的openid传递给js前段代码

        else:
            # 非初次授权
            user = oauth_qq_user.user  # 获得一个用户对象

            # 官方文档
            from rest_framework_jwt.settings import api_settings
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER  # 载荷的方法
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER  # 编码的方法
            payload = jwt_payload_handler(user)  # 用户通过载荷的方法生成一个载荷
            token = jwt_encode_handler(payload)  # 把载荷进行编码  /把用户信息编码成token

            # 合并购物车
            response = Response({
                "token": token,
                "username": user.username,
                "user_id": user.id
            })
            response = merge_cart(request, user, response)

            return response


    def post(self, request):
        # 获取参数
        dict_data = request.data

        # 创建序列化器
        serializer = self.get_serializer(data=dict_data)

        # 效验入库
        serializer.is_valid(raise_exception=True)
        user = serializer.save()

        # 根据用户数据生成token
        from rest_framework_jwt.settings import api_settings
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # 合并购物车,返回
        response = Response({
            "token": token,
            "username": user.username,
            "user_id": user.id
        })
        response = merge_cart(request, user, response)

        return response
